<?php
declare (strict_types = 1);

namespace app\common\model\mysql;

/**
 * @mixin \think\Model
 */
class Category extends BaseModel
{
    /**
     * 自动生成写入时间
     */
    protected $autoWriteTimestamp = true;

    /**
     * 获取正常状态下的对应字段数据
     *
     * @param string $field
     * @return Category[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getNormalCategory($field = true)
    {
        $where = ['status' => config('status.mysql.table_normal')];
        $order = ['listorder' => 'desc', 'id' => 'desc'];
        return $this->where($where)->field($field)->order($order)->select();
    }

    /**
     * 按条件获取分类分页数据
     *
     * @param array $data
     * @param int $number
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getLists(array $data)
    {
        $order = ['listorder' => 'desc', 'id' => 'desc'];

        $result = $this->where('status', '<>', config('status.mysql.table_delete'))
            ->where($data)
            ->order($order)
            ->select();
        return $result;
    }

    /**
     * 获取当前父级的所有子集栏目
     *
     * @param int $pid
     * @param string $field
     * @return mixed
     */
    public function getNormalByPid(int $pid = 0, string $field = "id,name,pid")
    {
        $where = ['status' => config('status.mysql.table_normal'), 'pid'    => $pid];
        $order = ['listorder' => 'desc', 'id' => 'desc'];
        $res   = $this->where($where)->field($field)->order($order)->select();
        return $res;
    }

    /**
     * 通过 PID 查找当前 ID 的子分类个数
     *
     * @param array $condition
     * @return mixed
     */
    public function getChildCountByPid(array $condition)
    {
        $where = [
            ['pid', 'in', $condition],
            ['status', '<>', config('status.mysql.table_delete')]
        ];

        $result = $this->where($where)->field('pid,count(*) as count')->group('pid')->select();

        return $result->toArray();
    }
}
